package com.finger.forest;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.finger.forest.adapter.CollectionListFireAdapter;
import com.finger.forest.adapter.CollectionListResourceAdapter;
import com.finger.forest.adapter.CollectionListRoadAdapter;
import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.CollectionRoadModel;
import com.finger.forest.model.FireInfoModel;
import com.finger.forest.model.ResourceModel;
import com.finger.forest.utils.ToastUtils;
import com.jakewharton.rxbinding2.view.RxView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;

/**
 * 信息列表（道路、火场、资源）
 */
public class CollectionListActivity extends BaseActivity<RegisterPresenter> implements BaseView {

    /**
     * 返回
     */
    @BindView(R.id.btn_back)
    ImageView backIv;

    //声明ViewPager
    private ViewPager mViewpager;

    //声明ViewPager的适配器
    private PagerAdapter mAdpater;

    //用于装载四个Tab的List
    private List<View> mTabs = new ArrayList<View>();

    /**
     * 道路
     */
    @BindView(R.id.tv_nav_road)
    TextView navRoadTv;

    /**
     * 火场
     */
    @BindView(R.id.tv_nav_fire)
    TextView navFireTv;

    /**
     * 资源
     */
    @BindView(R.id.tv_nav_resource)
    TextView navResourceTv;

    private List<CollectionRoadModel> collectionRoadModels = new ArrayList<>();
    private List<FireInfoModel> fireInfoModels = new ArrayList<>();

    private CollectionListRoadAdapter collectionListRoadAdapter;
    private CollectionListFireAdapter fireAdapter;


    private SmartRefreshLayout srlSmart;
    private SmartRefreshLayout fireSmart;
    private int firePage = 1;
    private int fireSize = 10;
    private boolean isFireRefresh;//火场刷新判断

    private SmartRefreshLayout resourceSmart;
    private int resourcePage = 1;
    private int resourceSize = 10;
    private boolean isResourceRefresh;//资源刷新判断

    private List<ResourceModel> resourceModels = new ArrayList<>();

    private CollectionListResourceAdapter collectionListResourceAdapter;

    /**
     * 跳转列表类型 0：道路；1：火场；2：资源。
     */
    private int type = 0;

    @Override
    protected int setView() {
        return R.layout.activity_collection_list;
    }

    @Override
    protected void receiveData() {
        Intent intent = getIntent();
        type = intent.getIntExtra("type",0);
    }

    @Override
    protected void initializeView() {
        initViews();
        initEvents();
        initDatas();

        clicks();
    }

    @Override
    protected void loadDataFromServer() {

    }

    //初始化控件
    private void initViews() {
        mViewpager = (ViewPager) findViewById(R.id.id_viewpager);

        //获取到四个Tab
        LayoutInflater inflater = LayoutInflater.from(this);
        View tab1 = inflater.inflate(R.layout.tab1, null);
        initTab1(tab1);

        View tab2 = inflater.inflate(R.layout.tab2, null);
        initTab2(tab2);

        View tab3 = inflater.inflate(R.layout.tab3, null);
        initTab3(tab3);

        //将三个Tab添加到集合中
        mTabs.add(tab1);
        mTabs.add(tab2);
        mTabs.add(tab3);
    }

    private void loadRoadInfomation() {
        Map<String, Object> maps = new HashMap<>();
        maps.put("userID", drUid);
        maps.put("token", token);
        maps.put("page", pageNUm);
        maps.put("rows", pageSize);
        presenter.loadRoadinformation(maps);
    }

    private void loadFireInfomation() {
        Map<String, Object> maps = new HashMap<>();
        maps.put("userID", drUid);
        maps.put("token", token);
        maps.put("page", firePage);
        maps.put("rows", fireSize);
        presenter.loadFireinformation(maps);
    }

    private void loadResourceInfomation() {
        Map<String, Object> maps = new HashMap<>();
        maps.put("userID", drUid);
        maps.put("token", token);
        maps.put("page", resourcePage);
        maps.put("rows", resourceSize);
        presenter.loadResourceInformation(maps);
    }

    /**
     * 初始化Tab2
     *
     * @param tab
     */
    private void initTab2(View tab) {
        fireSmart = tab.findViewById(R.id.fireSmart);
        RecyclerView rvFire = tab.findViewById(R.id.rvFire);
        fireAdapter = new CollectionListFireAdapter(R.layout.item_fire, fireInfoModels,CollectionListActivity.this);
        LinearLayoutManager fireLinearLayoutManager = new LinearLayoutManager(this);
        rvFire.setLayoutManager(fireLinearLayoutManager);
        rvFire.setAdapter(fireAdapter);

        fireSmart.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                firePage++;
                isFireRefresh = false;
                loadFireInfomation();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                firePage = 1;
                isFireRefresh = true;
                loadFireInfomation();
            }
        });

        fireSmart.autoRefresh();
    }

    /**
     * 初始化Tab1
     *
     * @param tab
     */
    private void initTab1(View tab) {
        srlSmart = tab.findViewById(R.id.srlSmart);
        srlSmart.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNUm++;
                isRefresh = false;
                loadRoadInfomation();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNUm = 1;
                isRefresh = true;
                loadRoadInfomation();
            }
        });
        srlSmart.autoRefresh();

        RecyclerView rvCollection = tab.findViewById(R.id.rvCollection);

        collectionListRoadAdapter = new CollectionListRoadAdapter(R.layout.item_road, collectionRoadModels,CollectionListActivity.this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        rvCollection.setLayoutManager(linearLayoutManager);
        rvCollection.setAdapter(collectionListRoadAdapter);
    }

    /**
     * 初始化Tab3
     *
     * @param tab
     */
    private void initTab3(View tab) {
        resourceSmart = tab.findViewById(R.id.resourceSmart);

        resourceSmart.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                resourcePage++;
                isResourceRefresh = false;
                loadResourceInfomation();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                resourcePage = 1;
                isResourceRefresh = true;
                loadResourceInfomation();
            }
        });
        resourceSmart.autoRefresh();

        RecyclerView rvResource = tab.findViewById(R.id.rvResource);

        collectionListResourceAdapter = new CollectionListResourceAdapter(R.layout.item_resource, resourceModels, CollectionListActivity.this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        rvResource.setLayoutManager(linearLayoutManager);
        rvResource.setAdapter(collectionListResourceAdapter);
    }

    private void initEvents() {
        //添加ViewPager的切换Tab的监听事件
        mViewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //获取ViewPager的当前Tab
                int currentItem = mViewpager.getCurrentItem();
                //将所以的TextView设置成黑色
                reseNavColor();
                //将当前Tab对应的TextView设置成蓝色
                switch (currentItem) {
                    case 0:
                        navRoadTv.setTextColor(getResources().getColor(R.color.colorBlue));
                        if (collectionRoadModels.size() == 0) {
                            loadRoadInfomation();
                        } else {
                            collectionListRoadAdapter.notifyDataSetChanged();
                        }
                        break;
                    case 1:
                        navFireTv.setTextColor(getResources().getColor(R.color.colorBlue));
                        if (fireInfoModels.size() == 0) {
                            loadFireInfomation();
                        } else {
                            fireAdapter.notifyDataSetChanged();
                        }
                        break;
                    case 2:
                        navResourceTv.setTextColor(getResources().getColor(R.color.colorBlue));
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void reseNavColor() {
        navRoadTv.setTextColor(getResources().getColor(R.color.black));
        navFireTv.setTextColor(getResources().getColor(R.color.black));
        navResourceTv.setTextColor(getResources().getColor(R.color.black));
    }

    private void initDatas() {
        //初始化ViewPager的适配器
        mAdpater = new PagerAdapter() {
            @Override
            public int getCount() {
                return mTabs.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                View view = mTabs.get(position);
                container.addView(view);
                return view;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(mTabs.get(position));
            }
        };
        //设置ViewPager的适配器
        mViewpager.setAdapter(mAdpater);
        //默认显示类型
        mViewpager.setCurrentItem(type);
    }

    private void clicks() {
        //返回
        RxView.clicks(backIv).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            finish();
        });

        //道路
        RxView.clicks(navRoadTv).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            mViewpager.setCurrentItem(0);
            if (collectionRoadModels.size() == 0) {
                loadRoadInfomation();
            } else {
                collectionListRoadAdapter.notifyDataSetChanged();
            }
        });

        //火场
        RxView.clicks(navFireTv).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            mViewpager.setCurrentItem(1);

            if (fireInfoModels.size() == 0) {
                loadFireInfomation();
            } else {
                fireAdapter.notifyDataSetChanged();
            }
        });

        //火场
        RxView.clicks(navResourceTv).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            mViewpager.setCurrentItem(2);
        });
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {
        switch (tag) {
            //道路
            case ResponseTag.ROAD_INFOMATION:
                List<CollectionRoadModel> collectionRoadModelList = (List<CollectionRoadModel>) model;
                if (null != collectionRoadModelList) {
                    if (isRefresh) {
                        collectionRoadModels.clear();
                    }
                    collectionRoadModels.addAll(collectionRoadModelList);
                }
                collectionListRoadAdapter.notifyDataSetChanged();

                finishSrlSmart();
                break;

            //火场列表
            case ResponseTag.FIRE_INFOMATION:
                List<FireInfoModel> fireInfoModelList = (List<FireInfoModel>) model;
                if (null != fireInfoModelList) {
                    if (isFireRefresh) {
                        fireInfoModels.clear();
                    }

                    fireInfoModels.addAll(fireInfoModelList);
                }
                fireAdapter.notifyDataSetChanged();

                finishFireSmart();
                break;

            //资源列表
            case ResponseTag.RESOURCE_INFOMATION:
                List<ResourceModel> resourceModelList = (List<ResourceModel>) model;
                if (null != resourceModelList) {
                    if (isResourceRefresh) {
                        resourceModels.clear();
                    }
                    resourceModels.addAll(resourceModelList);
                }
                collectionListResourceAdapter.notifyDataSetChanged();

                finishResourceSmart();
                break;
            default:
                break;
        }
        hidePd();
    }

    private void finishSrlSmart() {
        if (null != srlSmart) {
            srlSmart.finishRefresh();
            srlSmart.finishLoadMore();
        }
    }

    private void finishFireSmart() {
        if (null != fireSmart) {
            fireSmart.finishRefresh();
            fireSmart.finishLoadMore();
        }
    }

    private void finishResourceSmart() {
        if (null != resourceSmart) {
            resourceSmart.finishRefresh();
            resourceSmart.finishLoadMore();
        }
    }

    @Override
    public void onError(int errcode, int tag, String message) {
        hidePd();
        ToastUtils.show(message == null ? "网络异常" : message);

        finishSrlSmart();
        finishFireSmart();
        finishResourceSmart();
    }
}
